/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */

package com.ecarx.systemui.plugin.ui.navigationbar;

import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;

import com.ecarx.systemui.plugin.AppConstants;
import com.ecarx.systemui.plugin.NavigationBar;
import com.ecarx.systemui.plugin.R;
import com.ecarx.systemui.plugin.controller.hvac.FanSignalController;
import com.ecarx.systemui.plugin.ui.dialog.base.DialogManager;
import com.ecarx.systemui.plugin.model.listener.FanFuncNotifyViewListener;
import com.ecarx.systemui.plugin.model.listener.NoDoubleClickListener;
import com.ecarx.systemui.plugin.utils.LogUtils;
import com.ecarx.xui.adaptapi.FunctionStatus;

public class NavigationBarLeftFanView extends FrameLayout implements
        FanFuncNotifyViewListener {

    private final String TAG = "NavigationBarLeftFanViewTag";

    private FanSignalController fanSignalController;

    private ImageView ivFan;

    private NavigationBarClimateFanView navigationBarClimateFanView;

    public NavigationBarLeftFanView(@NonNull Context context) {
        this(context, null);
    }

    public NavigationBarLeftFanView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NavigationBarLeftFanView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.navigation_left_fan, this, true);
        ivFan = findViewById(R.id.iv_fan);
        ivFan.setOnClickListener(new NoDoubleClickListener(NoDoubleClickListener.NORMAL_SHORT_TIME) {
            @Override
            public void onNoDoubleClick(View view) {
                LogUtils.d(TAG, "CLICK FAN ICON fanSignalController:" + fanSignalController);
                if (fanSignalController == null) {
                    return;
                }
                boolean isSupportFanMode = fanSignalController.isSupportFanMode();
                LogUtils.d(TAG, "CLICK FAN ICON isSupportFanMode:" + isSupportFanMode);
                if (!isSupportFanMode) {
                    return;
                }

                boolean isHvacOn = fanSignalController.isHVACPowerOn();
                LogUtils.d(TAG, "isHvacOn:" + isHvacOn);

                if (!isHvacOn) {
                    fanSignalController.setHVACPowerOn(true);
                }

                DialogManager.getDialogManager().showFanControlDialog(getContext());

            }
        });
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (fanSignalController == null) {
            fanSignalController = FanSignalController.getInstance();
        }
        fanSignalController.setFanSignalNotifyViewListener(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (fanSignalController != null) {
            fanSignalController.setFanSignalNotifyViewListener(null);
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (ivFan != null) {
            //ivFan.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.fan_1));
        }
    }

    private void updateFanIcon(@DrawableRes int resId) {
        post(() -> {
            if (ivFan != null) {
                ivFan.setImageDrawable(AppCompatResources.getDrawable(getContext(), resId));
            }
        });
    }

    private void updateDockHandFanIcon(Integer value) {
        if (fanSignalController == null) {
            return;
        }
        int resId = AppConstants.getLeftHandFanIconByFanValue(value);
        if (resId != 0) {
            updateFanIcon(resId);
        }
    }

    @SuppressWarnings("unused")
    private void updateDockAutoFanIcon() {
        updateFanIcon(R.drawable.fan_auto);
    }

    private void updateClimateCenterFanIcon(boolean isAuto, int fanValueLevel) {
        //通知Dock中心空调图标更新
        post(() -> {
            if (navigationBarClimateFanView == null) {
                View rootView = NavigationBar.init(getContext()).getRootView();
                navigationBarClimateFanView = rootView.findViewById(R.id.navigationBarCenterView);
            }
            post(() -> navigationBarClimateFanView.updateFanLevel(isAuto, fanValueLevel));
        });
    }

    private void updateIconStatus(View view, FunctionStatus status) {
        post(() -> {
            if (FunctionStatus.active == status) {
                if (view != null) {
                    view.setAlpha(1f);
                    view.setEnabled(true);
                }
            } else {
                if (view != null) {
                    view.setAlpha(0.5f);
                    view.setEnabled(false);
                }
            }

            if (fanSignalController == null) {
                return;
            }
            boolean supportHandFan = fanSignalController.isSupportHandFan();
            boolean supportAutoFan = fanSignalController.isSupportAutoFan();
            LogUtils.d(TAG, "IS Active supportHandFan:" + supportHandFan +
                    ", supportAutoFan:" + supportAutoFan);
            if (supportHandFan || supportAutoFan) {
                ivFan.setVisibility(VISIBLE);
            } else {
                ivFan.setVisibility(GONE);
            }
            if (ivFan.getVisibility() == GONE) {
                setVisibility(GONE);
            } else {
                setVisibility(VISIBLE);
            }
        });
    }


    //------------------------------------信号回调开始------------------------------------------------

    /**
     * 通知风量模式变化
     *
     * @param isAuto 自动true、手动false
     */
    @Override
    public void onHvacModeChange(boolean isAuto, FunctionStatus functionStatus) {
        //风量模式该表后，会回调自动和手动风量信号，此处可以不处理
        LogUtils.d(TAG, "onHvacModeChange isAuto:" + isAuto);
        if (isAuto && fanSignalController != null) {
            int value = fanSignalController.getAutoFanValueLevel();
            updateDockAutoFanIcon();
            if (value != 255) {
                updateClimateCenterFanIcon(true, value);
            }
        }
    }

    /**
     * 通知手动风量值变化
     *
     * @param value 风量值
     */
    @Override
    public void onHvacHandFanChange(Integer value, FunctionStatus functionStatus) {
        LogUtils.d(TAG, "onHvacHandFanValueChange value:" + value);
        updateIconStatus(ivFan, functionStatus);
        updateDockHandFanIcon(value);
        updateClimateCenterFanIcon(false, value);
    }

    /**
     * 通知自动风量值变化
     *
     * @param value 风量值
     */
    @Override
    public void onHvacAutoFanChange(Integer value, FunctionStatus functionStatus) {
        LogUtils.d(TAG, "onHvacAutoFanValueChange value:" + value);
        updateIconStatus(ivFan, functionStatus);
        updateDockAutoFanIcon();
        updateClimateCenterFanIcon(true, value);
    }

    //------------------------------------信号回调结束------------------------------------------------


}
